<template>
	<!-- app -->
	<!-- #ifdef APP -->
	<view>
		<uni-forms validateTrigger="blur" ref="form" :modelValue="user" :rules="rules">
			<uni-forms-item label="用户名" name="username">
				<uni-easyinput type="text" v-model="user.username" placeholder="请输入用户名" />
			</uni-forms-item>
			<uni-forms-item label="密码" name="pwd">
				<uni-easyinput type="password" v-model="user.pwd" placeholder="请输入密码" />
			</uni-forms-item>
			<uni-forms-item>
				<button type="default" @tap="formSubmit">登录</button>
				<button type="warn" @tap="enterRegster">去注册</button>
			</uni-forms-item>
		</uni-forms>
	</view>
	<!-- #endif -->
	<!-- #ifdef MP-WEIXIN -->
	<button type="default">小程序一键登录</button>
	<!-- #endif -->
</template>

<script>
	export default {
		data() {
			return {
				rules: {
					username: {
						rules: [
							{
								pattern: /^[a-zA-Z]\w{3,7}$/,
								errorMessage: "以字母开头,4-8位英文数字_组成"
							},
							{
								required: true,
								errorMessage: "该字段必传"
							}
						]
					},
					pwd: {
						rules: [
							{
								pattern: /^[a-zA-Z]\w{3,7}$/,
								errorMessage: "以字母开头,4-8位英文数字_组成"
							},
							{
								required: true,
								errorMessage: "该字段必传"
							}
						]
					}
				},
				user: {
					username: '',
					pwd: ''
				},
				redirectUrl: ""
			}
		},
		methods: {
			
			// #ifdef MP-WEIXIN
			// 微信小程序授权登录
			loginInMpweixin() {
				// uni.login()拿到code
			},
			// #endif
			// #ifdef APP
			formSubmit(){
				this.$refs.form.validate().then(() => {
					this.$request('/user/username/login', {
						method: "POST",
						data: {
							...this.user,
							deviceId: '1111',
							deviceName: 'aaaa'
						}
					}).then(res => {
						if (res.code === 0) {
							uni.showToast({
								title:'登录成功'
							})
							uni.setStorageSync("token", res.data.token);
							uni.setStorageSync("uid", res.data.uid);
							// 跳转
							if (this.redirectUrl) {
								// 判断 redirectUrl是不是tab页
								const tabPages = ['/pages/home/home', '/pages/cate/cate', '/pages/cart/cart', '/pages/user/user'];
								if (tabPages.includes(this.redirectUrl)) {
									uni.switchTab({
										url:this.redirectUrl
									})
								} else {
									uni.redirectTo({
										url:this.redirectUrl
									})
								}
							} else {
								// 跳转到首页
								uni.switchTab({
									url:'/pages/home/home'
								})
							}
						}
					})
				}).catch(() => {
					console.log('校验失败');
				})
			},
			enterRegster(){
				uni.navigateTo({
					url:"/pages/register/register"
				})
			},
			// #endif
		},
		onLoad(options) {
			console.log(options);
			this.redirectUrl = options.redirect;
		}
	}
</script>

<style>

</style>